import { useDeepCompareEffect } from 'ahooks';
import { InputNumber, Space, Table } from 'antd';
import { useState } from 'react';

export default ({ value = [], onChange, loading }) => {
  const [dataSource, setDataSource] = useState([]);

  useDeepCompareEffect(() => {
    setDataSource(value);
  }, [value]);

  const handleEdit = async (record, code, value) => {
    const updatedDataSource = dataSource.map((item) => {
      if (item.itemSkuId === record.itemSkuId) {
        return { ...item, [code]: value };
      }
      return item;
    });

    setDataSource(updatedDataSource);
    onChange?.(updatedDataSource);
  };

  const orderTableProps = {
    bordered: true,
    dataSource,
    loading: loading,
    columns: [
      {
        title: '规格信息',
        dataIndex: 'skuName',
        width: 250,
      },
      {
        title: '售价',
        dataIndex: 'price',
        render: (_, record) => `￥${record.price}`,
        width: 120,
      },
      {
        title: 'sku库存',
        dataIndex: 'skuStock',
        width: 120,
      },
      {
        title: '积分库存',
        width: 120,
        dataIndex: 'pointsStock',
        render: (_, record) => (
          <InputNumber
            style={{ width: 90 }}
            min={0}
            step={1}
            max={record.skuStock}
            value={record.pointsStock}
            onChange={(value) => handleEdit(record, 'pointsStock', value)}
          />
        ),
      },
      {
        title: '积分配比',
        width: 300,
        dataIndex: 'pointsItemPrice',
        render: (_, record) => (
          <div>
            <Space>
              <span>￥</span>
              <InputNumber
                style={{ width: 90 }}
                min={0}
                step={0.01}
                value={record.pointsItemPrice}
                onChange={(value) => handleEdit(record, 'pointsItemPrice', value)}
              />
              <span>+</span>
              <InputNumber
                style={{ width: 90 }}
                min={0}
                step={1}
                value={record.pointsItemScore}
                onChange={(value) => handleEdit(record, 'pointsItemScore', value)}
              />
              <span>积分</span>
            </Space>
          </div>
        ),
      },
    ],
    rowKey: 'itemSkuId',
  };

  return <Table {...orderTableProps} />;
};
